package com.ljfiction.book.http;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ljfiction.book.activitys.ApplyAuthorActivity;
import com.ljfiction.book.activitys.BaseActivity;
import com.ljfiction.book.activitys.LoginActivity;
import com.ljfiction.book.tools.PreferencesTool;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/7/29.
 */

public class UserManageBean {
    private static boolean isLogin = false;//是否登录
    public static UserBean userBean = new UserBean();
    //public static Context context;
    private static String writerId = "";

    public static String getWriterId() {
        if (userBean != null) {
            return userBean.getUserId() + "";
        } else {
            return "";
        }
    }


    /**
     * 退出登录
     */

    public static void exit(Context context) {
        PreferencesTool.saveValue(context, "isCache", "");
        isLogin = false;//是否登录
        userBean = new UserBean();
    }


    /**
     * 获取用户ID
     *
     * @return
     */

    public static String getuserBeanId() {
        if (userBean != null && ("" + userBean.getUserId()) != null) {
            return userBean.getUserId() + "";
        }
        return "";
    }


    /**
     * 判断是否登录
     * @param context
     * @return
     */

    /*public static boolean isLogin(BaseActivity context) {
        if (isLogin){
            if(userBean==null||userBean.get()==null||userBean.getNickname().equals("")){
                goAddInfo(context);
                return false;
            }else {
                return true;
            }
        }else {
            goLogin(context);
        }
        return isLogin;
    }*/

    /**
     * 判断是否登录
     *
     * @param
     * @return
     */

    public static boolean isLogin() {
        return isLogin;
    }

    /**
     * 判断是否登录
     * @param context
     * @return
     */
    public static boolean isLogin(Context context) {
        if (isLogin){
            if(userBean==null||userBean.getPseudonym()==null||userBean.getPseudonym().equals("")){
                isLogin=false;
                goLogin(context);
            }else {
                return true;
            }
        }else {
            goLogin(context);
        }
        return isLogin;
    }
    /**
     * 判断是否是作者
     *
     * @param context
     * @return
     */

    public static boolean isAuthor(Context context) {
        if (isLogin) {
            if (StringTool.equals(userBean.getIsAuthor() + "", "1")) {
                return true;
            } else {
               Intent intent=new Intent(context, ApplyAuthorActivity.class);
                context.startActivity(intent);
                return false;
            }

        } else {
            return false;
        }
    }

    /**
     * 判断是否是作者  不提示
     *
     * @param context
     * @return
     */

    public static boolean isAuthor1(Context context) {
        if (isLogin) {
            if (StringTool.equals(userBean.getIsAuthor() + "", "1")) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }
    /**
     * 提示信息不全
     * @param context
     */

    /*public static void goAddInfo(final BaseActivity context) {
        OkDialog okDialog=new OkDialog(context,"信息不全,不能操作,是否补全信息?");
        okDialog.setListener(new OkDialog.Listener() {
            @Override
            public void okClick() {
               *//* new AddInfoDialog(context, new AddInfoDialog.Listener() {
                    @Override
                    public void ok() {
                    }
                    @Override
                    public void close() {
                    }
                });*//*
            }
            @Override
            public void closeClick() {
            }
        }, null, null);
        okDialog.setBigTitle("提示");
        okDialog.show();
    }*/

    /**
     * 提示不是作者
     *
     * @param context
     */

    public static void goAddAuthor(final Context context) {

    }

    /**
     * 跳转登录页面
     *
     * @param context
     */

    public static void goLogin(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    public static void setIsLogin(boolean isLogin) {
        UserManageBean.isLogin = isLogin;
    }


    /**
     * 查看缓存
     *
     * @param context
     * @return
     */

    public static String getCache(Context context) {
        String isCache = PreferencesTool.getValue(context, "isCache");
        if (!"".equals(isCache)) {
            return isCache;
        } else {
            return null;
        }
    }


    /**
     * 后台登录
     *
     * @param context
     */

    public static void backgroundLogin(Context context) {
        OkHttpUtils.post(HttpManager.IP + "/person-info")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Log.v("logion",s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserManageBean.userBean = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                isLogin=true;

                            }else if (!(UserManageBean.getCache(context) == null||(PreferencesTool.getUserName(context)).equals("") || (Md5.encryption(PreferencesTool.getPassWord(context))).equals(""))){
                                dologin(context);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    public static void dologin(Context context) {

        OkHttpUtils.post(HttpManager.IP + "/person-login")
                .params("userName",PreferencesTool.getUserName(context).toString())
                .params("userPassword", Md5.encryption(PreferencesTool.getPassWord(context).toString()))
                .params("terminal","2")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.v("dologin",s);
                        // 取得sessionid.
                        try {


                            Gson gson = new Gson();
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                userBean = user;
                                SettingManager.getInstance().savesessionId(userBean.getToken());
                                isLogin=true;
                            } else {
                               isLogin=false;
                            }

                        } catch (Exception e) {
                            UserManageBean.setIsLogin(false);
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onAfter(@Nullable String s, @Nullable Exception e) {
                        super.onAfter(s, e);
                       // UserManageBean.context=null;
                    }
                });
    }


    /**
     * 后台获取个人资料
     * @param context
     */


    /**
     * 后台更新财富
     *
     * @param context
     */
    public static void backgroundRiches(Context context) {
        if (!(getuserBeanId().equals(""))) {
           // UserManageBean.context = context;
        }
       if (!isLogin(context)){

           return;
       }else {
           OkHttpUtils.post(HttpManager.IP+"/person-info")

                  .execute(new StringCallback() {
                      @Override
                      public void onSuccess(String s, Call call, Response response) {
                          Gson gson = new Gson();
                          try {
                              JSONObject jsonObject = new JSONObject(s);
                              if ("200".equals(jsonObject.getString("returnCode"))) {
                                  UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                  UserManageBean.userBean = user;
                                  UserManageBean.setIsLogin(true);
                              } else {
                                  goLogin(context);
                              }

                          } catch (JSONException e) {
                              e.printStackTrace();
                          }

                      }
                  });
       }
    }
    /**
     * 后台登录结束 更新用户信息
     *
     * @param all
     */
/*
    * 更新用户信息（第三方登录）
    * */

     /**
     *  更新用户信息
     * @param all
     */


    /**
     * 更新用户财富
     *
     * @param all
     */

    private static void endRiches(JSONObject all) {
        try {
            String code = all.get("code") + "";
            if (code.equals("0")) {
                if (!all.has("result")) {
                    return;

                } else {
                    JSONObject result = all.getJSONObject("result");
                    if (UserManageBean.userBean == null) {
                        return;
                    }
                    //UserManageBean.userBean.setRiches(result);
                    //MineFragment.updataView();
                }
            } else {
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }



    /**
     * 设置等级和vip
     *
     * @param LV
     * @param VIP
     * @param lv
     * @param vip
     */

    public static void setLvAndVip(TextView LV, TextView VIP, String lv, String vip) {
        LV.setText("LV" + lv);
        LV.setVisibility(View.VISIBLE);
        if (vip.equals("1")) {
            VIP.setVisibility(View.VISIBLE);
        } else {
            VIP.setVisibility(View.GONE);
        }

    }
}
